package com.imist.jdbc.common;

import java.sql.*;

public class ConnectionUtil {
    private static String url = "jdbc:mysql://localhost:3306/message_board?useSSL=false&characterEncoding=UTF-8";
    private static String user = "root";
    private static String password = "123456";
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("找不到驱动程序类，加载驱动失败");
            e.printStackTrace();
        }
    }
    public ConnectionUtil() {
    }

    //获得数据库连接
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            System.out.println("创建数据库连接失败");
            e.printStackTrace();
        }
        return connection;
    }
    //释放数据库资源
    public static void release(Connection connection,Statement statement){

        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            statement = null;
        }
        if (connection != null){
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            connection = null;
        }
    }
    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            resultSet = null;
        }
        release(connection,statement);
    }
}
